﻿#include "hkCameraItem.h"


char jpegBuffer[10000000];

/** @brief 构造函数 */
HKCameraItem::HKCameraItem(QString name, QString ip, int port, QString usrName, QString pswd)
    : _cameraName(name), _cameraIp(ip), _cameraPort(port), _cameraUsrName(usrName), _cameraPassword(pswd)
{

}

HKCameraItem::~HKCameraItem(){


    return;

}


void HKCameraItem::run(){
    if(!isConnected){
        qDebug() << "相机" << _cameraName << "未连接，线程启动失败";
        _keepRun = false;
        return;
    }else{
        qDebug() << "相机" << _cameraName << "的线程开始run";
    }
    while(1){
        if(!_keepRun){
            qDebug() << "相机"<< _cameraName << "线程已终止";
            return;
        }
        captureImage();
        emit sigRefresh(_cameraName);
#ifdef Q_OS_WINDOWS
        Sleep(40);
#endif
#ifdef Q_OS_LINUX
//        sleep(40);
#endif
    }
}

void HKCameraItem::start(){

    startStopMutex.lock();
    _keepRun = true;
    QThread::start();
    int whileNum = 0;
    while(!QThread::isRunning()){
        Sleep(10);
        if(whileNum > 200){
            __LOG_ERROR("!!WhileCannotStop");
            qDebug() << "错误：CameraStart的while进入死循环，已强行终止";
            break;
        }
    }
    startStopMutex.unlock();
}
void HKCameraItem::stop(){
    startStopMutex.lock();
    _keepRun = false;
    int whileNum = 0;
    while(QThread::isRunning()){
        Sleep(10);
        if(whileNum > 200){
            __LOG_ERROR("!!WhileCannotStop");
            qDebug() << "错误：CameraStart的while进入死循环，已强行终止";
            break;
        }
    }
    startStopMutex.unlock();
}



/** @brief 连接摄像头设备 */
void HKCameraItem::connectCamera(){

    __LOG_FSTART__;

    qDebug() << ">>> startCamera [Start]";


    // 注册设备
    // 登录参数，包括设备地址、登录用户、密码等
    NET_DVR_USER_LOGIN_INFO struLoginInfo = {0};
    struLoginInfo.bUseAsynLogin = 0;
    strcpy(struLoginInfo.sDeviceAddress, _cameraIp.toLocal8Bit());   // 设备IP地址
    struLoginInfo.wPort = _cameraPort; // 设备服务端口
    strcpy(struLoginInfo.sUserName, _cameraUsrName.toLocal8Bit());
    strcpy(struLoginInfo.sPassword, _cameraPassword.toLocal8Bit());

    // 登录设备
    NET_DVR_DEVICEINFO_V40 struDeviceInfoV40 = {0};
    lUserID = NET_DVR_Login_V40(&struLoginInfo, &struDeviceInfoV40);
    if(lUserID < 0){
        auto errorCode = NET_DVR_GetLastError();
        qDebug() << ">>> Login failed, error code: " << errorCode;
        __LOG_FEND(errorCode);
        return;
    }
    qDebug() << ">>> Login Succeed lUserId=" << lUserID;

    // 播放配置
    NET_DVR_PREVIEWINFO struPlayInfo = {0};
    struPlayInfo.hPlayWnd = NULL;   // 需要SDK解码时句柄设为有效值，仅取流不解码时可设为空
    struPlayInfo.lChannel = 1;      // 预览通道号
    struPlayInfo.dwStreamType = 0;  // 0-主码流 1-子码流 2-码流3 ...
    struPlayInfo.dwLinkMode = 0;    // 0-TCP 1-UDP 2-多播 3-RTP 4-RTP/RTSP 5-RSTP/HTTP
    struPlayInfo.bBlocked = 1;      // 0-非阻塞取流 1-阻塞取流
    lRealPlayHandle = NET_DVR_RealPlay_V40(lUserID, &struPlayInfo, NULL, NULL);
    if(lRealPlayHandle < 0){
        qDebug() << ">>> NET_DVR_RealPlay_V40 error";
        NET_DVR_Logout(lUserID);
//        NET_DVR_Cleanup();
        return;
    }

    qDebug() << ">>> startCamera [Finished]";
    isConnected = true;
}

void HKCameraItem::logout(){
    NET_DVR_Logout(lUserID);
    isConnected = false;
}


///** @brief 启动定时捕获相机内容(已弃用) */
//void HKCameraItem::startCapturing(){

//    if(_timer) delete _timer;
//    _timer = new QTimer();
//    _timer->setInterval(100);
//    connect(_timer, SIGNAL(timeout()), this, SLOT(captureImage()));
//    _timer->start();

//}

/** @brief 捕获图像 */
void HKCameraItem::captureImage(){

    if(!isConnected)    return;
    if(!_provider)      return;

    NET_DVR_JPEGPARA jpegPara = {0};
    jpegPara.wPicSize = 500;
    jpegPara.wPicQuality = 2;
    DWORD resSize;
    bool res = NET_DVR_CaptureJPEGPicture_NEW(lUserID, 1, &jpegPara, jpegBuffer, (DWORD)1000000, &resSize);
    if(!res){
        qDebug() << "CaptureJpgePicture - Failed: " << NET_DVR_GetLastError();
    }
    _provider->lock();
    _provider->pm->loadFromData((uchar*)jpegBuffer, (uint)resSize);
//    _provider->pm = _image;
    _provider->unlock();

}

void HKCameraItem::setProvider(QSharedPointer<CameraImageProvider> provider){
    _provider = provider;
}

void HKCameraItem::clearProvider(){
    _provider = nullptr;
}
